package system

import (
	"github.com/gin-gonic/gin"
	"server/global"
	comRequest "server/model/common/request"
	"server/model/common/response"
	sysModel "server/model/system"
	sysRequest "server/model/system/request"
	sysService "server/service/system"
)

type UserApi struct {
}

//用户列表接口
func (u *UserApi) Index(c *gin.Context) {
	p := &sysRequest.SysUserGetList{}
	if err := c.ShouldBind(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userList, total, err := sysService.UserServiceApp.GetPageList(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//角色列表
	roleList, _, err := sysService.RoleServiceApp.GetList(&sysRequest.SysRoleGetList{})
	//转树结构数据
	roleTreeList := sysService.RoleServiceApp.BuildTree(roleList)
	//显示输出
	response.OkWithData(gin.H{
		"userList": userList,
		"total":    total,
		"pageNo":   p.PageNo,
		"roleList": roleTreeList,
		"permData": c.Value("permData"),
	}, c)
}

//保存用户数据
func (u *UserApi) Save(c *gin.Context) {
	p := &sysModel.SysUser{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	//如设置密码则存储加密密码
	if p.Password != "" {
		p.Password = sysService.UserServiceApp.Password(p.Password)
	}
	//保存用户数据
	if err := sysService.UserServiceApp.SaveUser(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}

//禁用用户
func (u *UserApi) Disable(c *gin.Context) {
	p := &comRequest.IdsReq{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := sysService.UserServiceApp.DisableUser(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}

//激活用户
func (u *UserApi) Enable(c *gin.Context) {
	p := &comRequest.IdsReq{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := sysService.UserServiceApp.EnableUser(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}
